'use strict';

app.controller('eventCtrl', ['$scope','$http','loginService', function($scope,$http,loginService){
	 $scope.init = function() {
		 loginService.islogged(); 
		 $scope.link = loginService.getLink();
		 $scope.type_filter_event = 0;
		 $scope.entryLimit = 10;
		 $scope.offset = 0;
		 $scope.disablePrev = true;
		 $scope.disableNext = false;
		 $scope.page_now = 1;
		 $scope.currentPage = 1;
	     $scope.list_event($scope.type_filter_event);
	     $scope.show_list_event = true;
	     $scope.event_detail_visible = false;
	     $scope.show_user_detail =  false;
	     
	     
	     //=====================event combox filter===============================
		 $scope.filter_event = [{
		      "event": "upcoming events",
		    	  "val": 1
		    }, 
		    { "event": "events in the past",
		    	"val": 2
		    }, 
		    { "event": "events now",
		    	"val": 3
		    }, 
		    { "event": "all events",
		    	"val": 4
		    }];
		 
		 $scope.selectedOption = $scope.filter_event[1];
		 
		//========================================================================
	    };
	     
	    //=====================paging list members of event======================
	    $scope.entryLimit_event = 5
	    $scope.offset_event = 0;
	    $scope.disablePrev_event = true;
	    $scope.disableNext_event = false;
	    $scope.page_now_event = 1;
	    //=======================================================================
	    
	  
	 $scope.list_event = function(type){
			$http.get($scope.link+'events').success(function(data,status, config){
				console.log('load list of events');
				$scope.model =  data;
				$scope.nb_row_notchange =  data.data.length;
				$scope.noOfPages = Math.ceil($scope.nb_row_notchange/$scope.entryLimit);
				$scope.jsonToArray(data, type);
			})
			.error(function(data, status, config) {
				console.log('can not load list of events');
		    }); 
	 }
	 
	  $scope.change = function() {
	    	var val = $scope.filter.val;
	    	$scope.type_filter_event = val;
	    	$scope.list_event(val);
	    	$scope.disablePrev = true;
	    	$scope.page_now=1;
	    	$scope.offset =0;
	    	//$scope.disableNext = true;
	    	if($scope.filter_ini <= $scope.entryLimit){ 
	    		$scope.disableNext = true;
	    	}
	    	//alert($scope.filter_filter);
	    	}
	  
	  $scope.jsonToArray = function (data, type) {
			$scope.a = new Array();  
			var i = 0;
			var j = 0;
			var f = 0;
			   var now = new Date();
				var today_datetime = Math.floor(now.getTime());
			 
			 angular.forEach(data.data,function(){
			  if( compare_event_with_today(data.data[i].start_time , data.data[i].end_time , type)){
                    $scope.a[f]=new Array(5);
					$scope.a[f][0] =  data.data[i].id;
		    		$scope.a[f][1] =  data.data[i].name;
		    		$scope.a[f][2] =  data.data[i].interest;
		    		$scope.a[f][3] =  data.data[i].start_time;
		    		$scope.a[f][4] =  data.data[i].end_time;
	                 f++;
				}
				i++;
				
	        })
	        $scope.nb_row_event = f; 
			$scope.filter_filter = f;
			$scope.a_ini= angular.copy($scope.a);
			$scope.noOfPages = Math.ceil($scope.nb_row_event/$scope.entryLimit);
			if($scope.filter_filter <= $scope.entryLimit){
				$scope.disableNext = true;
			}
			else
				$scope.disableNext = false;
//	    /alert($scope.filter_filter);
			
		}

		// switch to next page
		$scope.nextPage = function() {  //alert($scope.filtered.length);
			nextPage_event($scope);
		}
		
		// switch to previous page
		$scope.previousPage = function() {
			previousPage_event($scope);
		}
		
		// switch to next page
		$scope.nextPage_event = function() { 
			nextPage_event_users($scope);
		}
		
		// switch to previous page
		$scope.previousPage_event = function() {
			previousPage_event_users($scope);
		}
		
		
		$scope.filter_event = function () {
			$scope.filtered_search = angular.copy($scope.filtered);
			if($scope.nb_row_notchange == $scope.filtered.length)
			   $scope.filtered_ini = angular.copy($scope.filtered);
		 
			if( !angular.isUndefined($scope.search1) ) {
			
				if( !angular.isUndefined($scope.filtered_ini) )  {
					$scope.recalculate_array($scope.filtered_ini);
					$scope.disablePrev = true;
				}
				$scope.filter_ini = $scope.filtered.length;
			}
			
         }
		
		
		  $scope.recalculate_array = function (data) { 
				 $scope.a = new Array();
				 var i = 0;
				 angular.forEach(data,function(){
					 $scope.a[i]=new Array(5);
					 var splitted =  ((data[i]).toString()).split(',') ;
					  $scope.a[i][0] =  splitted[0];
				      $scope.a[i][1] =  splitted[1];
					  $scope.a[i][2] =  splitted[2];
					  $scope.a[i][3] =  splitted[3];
					  $scope.a[i][4] =  splitted[4];
					  i++;

		         })
		         $scope.nb_row_event = i ;
				
			 }
		  
		    
		  $scope.$watch('b', function() {   
			if( ($scope.page_now_event==1)  &&  ($scope.nbr_rows_attendings <= $scope.entryLimit_event) )
				 {
				 $scope.disableNext_event = true;
				 }
				
			}); 
		  
		  
	
		    
		  
			$scope.$watch('filtered', function() {
				 if( !angular.isUndefined($scope.search1) ) { 
						$scope.filter_ini = $scope.filtered.length;
					}
				
				 if($scope.search1 ==''){  
						$scope.filter_ini = $scope.nb_row_notchange;
				 }
				
				
				 if( ($scope.page_now==1)  &&  ( ($scope.filter_ini <= $scope.entryLimit) ||  ($scope.filter_filter<=$scope.entryLimit) )){
					 if(!angular.isUndefined($scope.search1)){ //search has some thing
						    if(!$scope.click_prev)
						    	$scope.disableNext = true;
						}
					 else
						 $scope.disableNext = true;
				 }
 			     else if(($scope.page_now==1) &&  ($scope.filter_ini > $scope.entryLimit)){
				     $scope.disableNext = false;
			      }
				
				//alert($scope.page_now);
				 if( ($scope.page_now==$scope.noOfPages)  &&  ($scope.filter_ini <= $scope.entryLimit) )
		 				$scope.disablePrev = true;
			     else if(($scope.page_now==$scope.noOfPages) &&  ($scope.filter_ini > $scope.entryLimit)){
						 $scope.disablePrev = false;
			     }
				
				
				 if(($scope.page_now!=1) && ($scope.page_now!=$scope.noOfPages)){//alert('totoo');
				     if ( $scope.filter_ini < $scope.entryLimit){
						 $scope.disableNext = true;
	                     $scope.disablePrev = true;
					 }
					 else{//alert($scope.noOfPages);
						 $scope.disableNext = false;
						 //$scope.disablePrev = false;
					 }
				 }
				
				
				
			});
			
			
			$scope.event_go = function(eventId, type_return,eventId_) { 
//				show_group_detail = 1;
//				show_list_group = 0;
//				show_user_detail = 0;
				$scope.show_list_event = false;
				$scope.event_detail_visible = true;
				$scope.getEventByEventId(eventId);
				
				$scope.type_return = type_return;
			    $scope.event_id = eventId_;
			};
			
			 $scope.getEventByEventId = function(id){
			        $http.get($scope.link+'event/'+id).success(function(data){
			        	console.log('an event is loaded');
			        	$scope.event = data;
			        	$scope.getUserById(data.data.owner_id,1);
			        	var loc = data.data.location;
			        	var loc_Str = loc.toString();
			        	var arr  = loc_Str.split(",") ; 
			        	$scope.long = arr[0];
			        	$scope.lat = arr[1];
			        	
			        	$scope.getUsersByEventId(id);
			        	$scope.getGroupByGroupId(data.data.group_id);
			        }).error(function(data, status, config) {
			        	console.log('can not load event with event id : ' + id);
			 });
			 }
			 
			 $scope.getGroupByGroupId = function(id){
			        $http.get($scope.link+'group/'+id).success(function(data){
			        	console.log('a group is loaded');
			        
//			        	$scope.getUserById_group(data.data.owner_id);
//			        	
//			        	var loc = data.data.location;
//			        	var loc_Str = loc.toString();
//			        	var arr  = loc_Str.split(",") ; 
//			        	$scope.long = arr[0];
//			        	$scope.lat = arr[1];
			        	
			        	//$scope.getUsersByGroupId(id);
			        	
			        }).success(function(data, status, config) {
			        	 $scope.name_gr = data.data.name;
			 });
			 }
			 
			 
			 $scope.getUsersByEventId = function(id){
			        $http.get($scope.link+'user_event/'+id).success(function(data){
			        	console.log('list users by event id is loaded');
			        	$scope.lst_user = data;
			        	
			        	$scope.nb_users = data.data.attendings_list.length;
			        	//alert($scope.nb_users);
			        	
                    	$scope.jsonToArray_members(data);
			        	pageResult_event($scope);
			        }).error(function(data, status, config) {
			        	console.log('can not load list of users by event Id : ' + id);
			 });
			 }
			 
			 $scope.jsonToArray_members = function (data) { //alert(JSON.stringify(data));
					$scope.b = new Array();
					var i = 0;
					angular.forEach(data.data.attendings_list,function(){
						$scope.b[i]=new Array(2);
			    		
						$scope.b[i][1] =  data.data.attendings_list[i].id;
						var id = data.data.attendings_list[i].id;
						$scope.getUserById(id,2);
						$scope.b[i][0] =  $scope.name;
						
			            i++;
			        })
			        $scope.nbr_rows_attendings = i ;
					$scope.b_ini= angular.copy($scope.b);
				}
			 
			 $scope.getUserById = function(id, type){
				var name = 'not_name';
			        $http.get($scope.link+'users/'+id).success(function(data){
			        	console.log('owner is loaded');
			            if(type==1){
			        	  $scope.owner = data;
			            }
			        	
			         
			        	 $scope.getGroupsByUserId(data.data.id);
			        }).success(function(data, status, config) {
			        	 $scope.name = data.data.first_name + ' ' + data.data.last_name;
			        });
			    
			    
			 }
			 
			 
			 $scope.lock = function(userid,id){
				  if(id==0){
					
					
						  $http.get($scope.link+'user_bl/'+userid).success(function(data){
					        	console.log('user is locked');
					        	//$scope.lock = data;
					         	//$scope.list_user($scope.offset,$scope.page_now);
					         }).error(function(data, status, config) {
					        	console.log('can not lock user with id : ' + userid);
					       });
					 
					  
					 
				  }
				  else if(id==1){
					  $http.get($scope.link+'user_ubl/'+userid).success(function(data){
				        	console.log('user is unlocked');
				        	$scope.unlock = data;
				        	//alert('unlock :   '  +  JSON.stringify(data));
				        	//$scope.getGroupsByUserId(data.data.id);
				        	// $scope.list_user($scope.offset,$scope.page_now);
				         }).error(function(data, status, config) {
				        	console.log('can not un lock user with id : ' + userid);
				       });  
				  }
				  
				  $scope.getUserById(userid,1);
				  $scope.go_user_detail(userid,1);  
				 
			 }
			 
			 
			 $scope.go_user_detail = function(user,id) {
				  $scope.show_list_event = false;
				  $scope.event_detail_visible = false;
				  $scope.show_user_detail =  true;
				  $scope.getUserById(user,1);
				  // alert(JSON.stringify($scope.owner));
				    
				};
			 
			 $scope.return_to_list_event = function(user,id) {
				  if ( $scope.type_return ==1){
					  $scope.show_list_event = true;
				      $scope.event_detail_visible = false; 
				  }
				  else if ( $scope.type_return ==2){
//					  show_user_detail = 1;
//					  show_group_detail = 0;
//					  show_list_group = 0;
//					  $scope.type_return = 1;
//					  $scope.go_user_detail($scope.user_id,1);
				  }
				};
				
				
				$scope.return_to_event_detail = function(user,id) {
					if ( $scope.type_return ==1){
						 $scope.show_list_event = false;
						 $scope.event_detail_visible = true;
						 $scope.show_user_detail =  false;
					   // $scope.list_groups();
					}
					
					else if ( $scope.type_return ==2){
//						//show = 1;
//						show_group_detail = 1;	
//						show_user_detail = 0;
//						$scope.type_return = 1;
					}
					
				};	
	
	
}])